package com.lml.leetcode;

/**
 * @author Administrator
 * @date 2020/3/22 10:44
 * Description:
 */
public class DemoTest07 {

    public static void main(String[] args) {
        int testNum = 1534236469;
        int reverse = reverse2(testNum);
        System.out.println(reverse);
    }

    /**
     * 7. 整数反转
     * https://leetcode-cn.com/problems/reverse-integer/
     *
     * @param x 要反转的数字
     * @return 反转后的数字
     */
    public static int reverse(int x) {
        if (x == 0) return 0;
        StringBuffer sb = new StringBuffer(String.valueOf(x));
        String numStr = sb.reverse().toString();
        //如果是负数就做个标记
        boolean endWithMinus = numStr.endsWith("-");
        numStr = endWithMinus ? numStr.substring(0, numStr.length() - 1) : numStr;
        for (int i = 0; i < numStr.length(); i++) {
            //如果数字开头为0,就循环去掉
            if (numStr.startsWith("0")) {
                numStr = numStr.substring(1);
            }
        }
        numStr = endWithMinus ? "-" + numStr : numStr;
        return Integer.parseInt(numStr);
    }

    public static int reverse2(int x) {
        if (x == 0) return 0;
        StringBuilder answerStr = new StringBuilder();
        int length = String.valueOf(x).length();
        int temp = 0;
        for (int i = 0; i < length; i++) {
            if ((temp = x % 10) != 0) {
                answerStr.append(temp);
                x = x / 10;
                System.out.println(x);
                System.out.println("answerStr = " + answerStr);
            }
        }
        int answer = Integer.parseInt(answerStr.toString());
        return temp > 0 ? answer : -answer;
    }
}
